from django.db import DatabaseError
from rest_framework.response import Response
from rest_framework.views import exception_handler as drf_exception_handler
from rest_framework import serializers
from rest_framework import status
import logging

logger = logging.getLogger('django')


def get_validation_error_content(errors):
    content = dict()
    for key, value in errors.items():
        content[key] = str(value[0])

    return content


# 在原有DRF异常基础上增加数据库异常处理
def exception_handler(exc, context):
    """
    自定义异常处理
    :param exc: 异常
    :param context: 抛出异常的上下文
    :return: Response响应对象
    """
    # 获取发生异常的视图函数
    view = context['view']

    if isinstance(exc, serializers.ValidationError):
        content = get_validation_error_content(exc.detail)
        logger.info('[%s]: %s' % (view, content))
        return Response(content, status=status.HTTP_400_BAD_REQUEST)

    elif isinstance(exc, DatabaseError):
        logger.error('[%s]: %s' % (view, exc))
        return Response("数据库错误", status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    # 调用drf框架原生的异常处理方法
    response = drf_exception_handler(exc, context)
    if response is None:
        logger.error('[%s]: %s' % (view, exc))
        return Response("服务器内部错误", status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    return response
